package nbcp.db.redis.proxy

import io.lettuce.core.RedisClient
import io.lettuce.core.api.sync.RedisCommands
import io.lettuce.core.codec.ByteArrayCodec
import nbcp.base.extend.AsInt
import nbcp.base.extend.ToMap
import nbcp.base.extend.*
import nbcp.base.utils.SpringUtil
import nbcp.db.redis.RedisConfig
import java.io.Serializable

/**
 * Created by yuxh on 2018/6/7
 */


class RedisSessionProxy(
        collectionName: String,
        dbOffset: Int = 0,
        var defaultCacheSeconds: Int = 0) : BaseRedisVarKeyProxy(dbOffset, collectionName) {


//    fun hkeys(key: String):  List<String>  {
//        return redis.hkeys(key.toByteArray()).map { it.contentToString() }
//    }


    fun get(token_value: String, field: String): ByteArray = redis.byteArrayCommand(dbOffset) {
        it.hget(collectionName + ":" + token_value, field);
    }

    private fun get(token_value: String): Map<String, Serializable> {
        var keys = redis.byteArrayCommand(dbOffset) { it.hkeys(token_value) }
        if (keys.any() == false) return linkedMapOf();
        var ret = redis.byteArrayCommand(dbOffset) { it.hmget(collectionName + ":" + token_value, *keys.toTypedArray()) }
        return ret.ToMap({ it.key }, { it.value.ToSerializableObject() })
    }

    fun set(token_value: String, value: Map<String, Serializable>): String {
        if (value.any() == false) return "";

        return redis.byteArrayCommand(dbOffset) { it.hmset(collectionName + ":" + token_value, value.ToMap({ it.key }, { it.value.ToSerializableByteArray() })) }
    }
}